package pl.ppsoft.fixlang;

import pl.ppsoft.fixlang.common.HandleEvent;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class LessonsManagerActivity extends ListActivity {

	private static final int REQUEST_WORD_MANAGER = 1;
	private static final int REQUEST_CODE_PREFERENCES = 2;	
	
	public static final int ADD_LESSON_DIALOG = 1;
	public static final int EDIT_LESSON_DIALOG = 2;
	public static final int DEL_LESSON_DIALOG = 3;
	public static final int ARCHIVE_LESSON_DIALOG = 4;
	public static final int UNARCHIVE_LESSON_DIALOG = 5;
		
    private DbAdapter db;
    private SharedPreferences settings;
	private String sortCol = DbAdapter.LESSON_ROWID;
	private boolean sortDesc = false;
    private Cursor lessonsCursor;
    private int selectedPosition;
    private int statusColIndex;
    private long selectedLessonId;
    
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lesson_manager);
        
        this.settings = PreferenceManager.getDefaultSharedPreferences(this);
        db = new DbAdapter(this);
        db.open();

        registerForContextMenu( getListView() );        
                
        loadLessons(sortCol, sortDesc);
    }
	
	@Override
	protected void onDestroy() {
		db.close();

		super.onDestroy();
	}

	private void loadLessons( String sort, boolean desc ) {
		if ( lessonsCursor != null ) {
			lessonsCursor.close();
		}

		lessonsCursor = db.fetchManageLessons(sort, desc);
		
        startManagingCursor(lessonsCursor);

        String[] from = new String[]{DbAdapter.LESSON_NAME, DbAdapter.LESSON_WORD_COUNT, DbAdapter.LESSON_STATUS};
        int[] to = new int[]{R.id.lesson, R.id.wordcount, R.id.archive_icon};
        
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.lesson_manager_row, lessonsCursor, from, to);
        
		final int countColIndex = lessonsCursor.getColumnIndexOrThrow( DbAdapter.LESSON_WORD_COUNT );
		statusColIndex = lessonsCursor.getColumnIndexOrThrow( DbAdapter.LESSON_STATUS );
        adapter.setViewBinder( new SimpleCursorAdapter.ViewBinder() {			
			@Override
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				if ( columnIndex == countColIndex ) {
			    	int count = cursor.getInt(columnIndex);
			    	String text = count + " ";
			    	if ( count == 1 ) {
			    		text += getString( R.string.oneword );
			    	} else if ( count >= 1 && count <= 4 ) {
			    		text += getString( R.string.twofourword );
			    	} else {
			    		text += getString( R.string.restword );
			    	}	    	
			    	((TextView)view).setText(text); 					
					return true;
				} else if ( columnIndex == statusColIndex ) {
					int status = cursor.getInt(columnIndex);
					view.setVisibility((status==DbAdapter.LESSON_STATUS_DO_ARCHIVE||status==DbAdapter.LESSON_STATUS_ARCHIVED)?View.VISIBLE:View.GONE);
					return true;
				}
				return false;
			}
			
		});		
        
        setListAdapter(adapter);   
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.lessons_manager_menu, menu);
                
        return super.onCreateOptionsMenu(menu);
    }

    @Override
	public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menu_sync).setVisible(this.settings.getBoolean(ConfigActivity.SYNC_PREFERENCE, false) );        

    	return super.onPrepareOptionsMenu(menu);
	}
    
    
    private void onModify() {
        Editor editor = settings.edit();
        editor.putBoolean(FixLangActivity.MODIFY_PREFERENCE_FLAG, true);
        editor.commit();
        
        lessonsCursor.requery();
    }
    
    private void doSyncLessons() {
        String url = settings.getString(ConfigActivity.URL_PREFERENCE, ""); 
        HandleEvent handler = new HandleEvent() {			
			@Override
			public boolean doEvent() {
				onModify();				
				return true;
			}
		};
        
    	new SyncLessonsTask(this, db, url, handler ).execute();    	
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
	        case R.id.menu_config:
	        	Intent config = new Intent(this, ConfigActivity.class);
	        	config.putExtra(ConfigActivity.PREFERENCE_MODE_PARAM, R.xml.manager_preferences);
	        	startActivityForResult(config, REQUEST_CODE_PREFERENCES);             	
	            return true;
	        case R.id.menu_sync:
	        	this.doSyncLessons();
                return true;
            case R.id.menu_sort_name:
            	sortList( item,DbAdapter.LESSON_NAME, false ); 
            	return true;
            case R.id.menu_sort_words:
            	sortList( item,DbAdapter.LESSON_WORD_COUNT, true ); 
            	return true;
            default:
                return super.onOptionsItemSelected(item);                
        }
    }
    
    private void sortList(MenuItem item, String name, boolean desc) {
    	if ( sortCol.equals( name ) ) {
    		sortDesc = !sortDesc;
    	} else {
    		sortDesc = desc;
    	}
    	item.setChecked(true);
    	sortCol = name;
    	loadLessons( name, sortDesc );     	
    }
 
    @Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ADD_LESSON_DIALOG:
            final View lessonAddView = LayoutInflater.from(this).inflate(R.layout.lesson_dialog, null); 
            
	         return new AlertDialog.Builder(this)
             .setTitle(R.string.lesson_add_title)
             .setView(lessonAddView)
             .setPositiveButton(R.string.btn_add, new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int whichButton) {                	 
                     EditText nameEdit = (EditText)lessonAddView.findViewById( R.id.lesson_name );
                     String value = nameEdit.getText().toString();                     
                     if ( value == null || value.length() == 0 ) {
                    	 Toast.makeText(LessonsManagerActivity.this, R.string.lesson_name_empty, Toast.LENGTH_LONG).show();
                     } else {                     
	                	 db.addLesson( value );
	                	 onModify();
                     }
                 }
             })
             .setNegativeButton(R.string.btn_cancel, null)
             .create();     				
		case EDIT_LESSON_DIALOG:
			View lessonEditView = LayoutInflater.from(this).inflate(R.layout.lesson_dialog, null); 

			final EditText nameEdit = (EditText)lessonEditView.findViewById( R.id.lesson_name );

			return new AlertDialog.Builder(this)
			.setTitle(R.string.lesson_edit_title)
			.setView(lessonEditView)
			.setPositiveButton(R.string.btn_save, new DialogInterface.OnClickListener() {
			     public void onClick(DialogInterface dialog, int whichButton) {
                     String value = nameEdit.getText().toString();                     
                     if ( value == null || value.length() == 0 ) {
                    	 Toast.makeText(LessonsManagerActivity.this, R.string.lesson_name_empty, Toast.LENGTH_LONG).show();
                     } else {                     
    			    	 db.updateLesson( selectedLessonId, value );
    			    	 onModify();
                     }
			     }
			 })
			.setNegativeButton(R.string.btn_cancel, null)
			.create();     				
		case DEL_LESSON_DIALOG:
        	return new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setMessage(R.string.lesson_really_delete)
            .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                	db.deleteLesson(selectedLessonId);
                	onModify();
                }

            })
            .setNegativeButton(R.string.btn_no, null)
            .show();
		case ARCHIVE_LESSON_DIALOG:        	
        	return new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setMessage(R.string.lesson_really_archive)
            .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                	db.archiveLesson( selectedLessonId );
                	onModify();
                }

            })
            .setNegativeButton(R.string.btn_no, null)
            .create();			        	
		case UNARCHIVE_LESSON_DIALOG:        	
        	return new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setMessage(R.string.lesson_really_unarchive)
            .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                	db.unarchiveLesson( selectedLessonId );
                	onModify();
                }

            })
            .setNegativeButton(R.string.btn_no, null)
            .create();			        	        	
		default:
	    	return super.onCreateDialog(id);
		}
	}

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.lesson_modify_menu, menu);
    	    	    	
    	Cursor row = (Cursor)getListView().getItemAtPosition( ((AdapterContextMenuInfo) menuInfo).position );
    	boolean normal = row.getInt(statusColIndex) > 1;
		menu.findItem( R.id.menu_editlesson ).setVisible(normal);
		menu.findItem( R.id.menu_dellesson ).setVisible(normal);
		menu.findItem( R.id.menu_archivelesson ).setVisible(normal);
		menu.findItem( R.id.menu_unarchivelesson ).setVisible(!normal);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo ) item.getMenuInfo();
    	selectedPosition = info.position;
    	selectedLessonId = info.id;
    	switch(item.getItemId()) {
	    	case R.id.menu_editlesson:
	        	this.showDialog(EDIT_LESSON_DIALOG);        	
	        	return true;
	        case R.id.menu_dellesson:
	        	this.showDialog(DEL_LESSON_DIALOG);        	
	        	return true;
	        case R.id.menu_archivelesson:
	        	this.showDialog(ARCHIVE_LESSON_DIALOG);        	
	        	return true;
	        case R.id.menu_unarchivelesson:
	        	this.showDialog(UNARCHIVE_LESSON_DIALOG);        	
	        	return true;
	        default:
	            return super.onContextItemSelected(item);
        }    	
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	Cursor row = (Cursor)l.getItemAtPosition(position);
    	if ( row.getInt(statusColIndex) > 1 ) {    	
	    	Intent word = new Intent(this, WordsManagerActivity.class);
	    	word.putExtra(WordsManagerActivity.LESSON_ID_PARAM, id);
	    	word.putExtra(WordsManagerActivity.LESSON_NAME_PARAM, ((TextView)v.findViewById( R.id.lesson )).getText() );
	    	startActivityForResult(word, REQUEST_WORD_MANAGER);
    	}
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_WORD_MANAGER) {        	
        } else if (requestCode == REQUEST_CODE_PREFERENCES) {        	
        }
    }

    public void onAddLesson(View v) {
    	this.showDialog(ADD_LESSON_DIALOG);    	
    }
    
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);

    	EditText text = (EditText)dialog.findViewById( R.id.lesson_name );
        switch (id) {
            case ADD_LESSON_DIALOG:
            	text.setText("");
            	break;
            case EDIT_LESSON_DIALOG:
            	Cursor row = (Cursor)getListView().getItemAtPosition(this.selectedPosition);
    			text.setText( row.getString( row.getColumnIndex( DbAdapter.LESSON_NAME ) ) );
            	break;            	
        }
    }

	@Override
	protected void onResume() {
        if ( this.settings.getBoolean(FixLangActivity.MODIFY_PREFERENCE_FLAG, false) ) {
            Editor editor = this.settings.edit();
            editor.remove(FixLangActivity.MODIFY_PREFERENCE_FLAG);
            editor.commit();

        	lessonsCursor.requery();
        }
		
		super.onResume();
	}

	public void onSyncClick(View view) {
		if ( this.settings.getBoolean(ConfigActivity.SYNC_PREFERENCE, false) ) {
			this.doSyncLessons();	
		} else {
    		new AlertDialog.Builder(this)
    		.setMessage(R.string.sync_preference_required)
    		.setNeutralButton(R.string.btn_ok, null )                    
    		.show();        					
		}    	
    }
	
}
